package com.compdev.testutils.clipboard;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class ClipBoardManager  implements ClipboardOwner {

	public void writeText(String stringToWriteToClipboard){
		
		// get the system clipboard
		Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		
		// set the textual content on the clipboard to our 
		// Transferable object
		// we use the 
		Transferable transferableText = new StringSelection(stringToWriteToClipboard);
		systemClipboard.setContents(transferableText,this);
		
	}
	
	// see http://www.javapractices.com/topic/TopicAction.do?Id=82
	  public String getText() {
		    String result = "";
		    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

		    Transferable contents = clipboard.getContents(null);

		    boolean hasTransferableText =
		      (contents != null) &&
		      contents.isDataFlavorSupported(DataFlavor.stringFlavor)
		    ;
		    if ( hasTransferableText ) {
		      try {
		        result = (String)contents.getTransferData(DataFlavor.stringFlavor);
		      }
		      catch (UnsupportedFlavorException ex){
		        //highly unlikely since we are using a standard DataFlavor
		        System.out.println(ex);
		        ex.printStackTrace();
		      }
		      catch (IOException ex) {
		        System.out.println(ex);
		        ex.printStackTrace();
		      }
		    }
		    return result;
		  }

	@Override
	public void lostOwnership(Clipboard arg0, Transferable arg1) {
	}
	

}
